//
//  GameListBaseViewController.m
//  YoucApp
//
//  Created by Liam on 11/12/12.
//
//

#import "GameListBaseViewController.h"
#import "EGORefreshTableHeaderView.h"
#import "EGORefreshTableFooterView.h"

@interface GameListBaseViewController()

@property (retain, nonatomic) NSArray *currentShowList;             // 当前显示的列表
@property (assign, nonatomic) BOOL loading;
@property (retain, nonatomic) EGORefreshTableHeaderView *refreshHeaderView;
@property (retain, nonatomic) EGORefreshTableFooterView *refreshFooterView;

@end

@implementation GameListBaseViewController

@synthesize tableView = _tableView;

@synthesize currentShowList = _currentShowList;
@synthesize gameList = _gameList;

- (id)init
{
    self = [self initWithNibName:@"GameListViewController" bundle:nil];
    
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
		self.navigationItem.hidesBackButton = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
	
	//self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"wy_gamelist_bg.png"]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getGameListDidFinished:) name:[self gameListNotificationName] object:nil];

	[self performSelector:@selector(loadFirstList) withObject:nil afterDelay:0.1];
    
    self.title = @"微游";
	
	//self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:[[[UIView alloc] initWithFrame:CGRectZero] autorelease]] autorelease];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:[self gameListNotificationName] object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    self.tableView = nil;
    self.currentShowList = nil;
    self.gameList = nil;
	self.refreshHeaderView = nil;
	self.refreshFooterView = nil;
    [super viewDidUnload];
}

- (void)dealloc {
    [_tableView release];
    [_currentShowList release];
    [_gameList release];
	[_refreshHeaderView release];
	[_refreshFooterView release];
    [super dealloc];
}

- (void)constructCurrentShowList
{
    self.currentShowList = [self getShowList];
    [self.tableView reloadData];
}

- (void)loadFirstList
{
	if ([self.gameList count] == 0)
    {
		self.loading = YES;

		[self.refreshHeaderView startRefreshScrollView:self.tableView];

		self.loading = [self loadList:[self.gameList count] limit:10];
	}
}

//- (void)clearList
//{
//	self.currentShowList = nil;
//	[self.tableView reloadData];
//}

- (id)itemAtIndexPath:(NSIndexPath *)indexPath
{
	NSInteger index = [indexPath row];
	if (index < [self.currentShowList count])
	{
		return [self.currentShowList objectAtIndex:index];
	}
	return nil;
}

- (NSArray *)deleteItemAtIndexPath:(NSIndexPath *)indexPath
{
	NSMutableArray *indexPaths = [NSMutableArray array];
	
	id item = [self itemAtIndexPath:indexPath];
	if (item)
	{
		NSArray * assItems = [self getAssociateItems:item];
		if (assItems)
		{
			NSMutableArray * array = [NSMutableArray arrayWithArray:self.currentShowList];
			NSMutableIndexSet * removeIndexes = [NSMutableIndexSet indexSet];
			
			for (id object in assItems)
			{
				NSUInteger index = [array indexOfObject:object];
				if (index != NSNotFound)
				{
					[removeIndexes addIndex:index];

					NSIndexPath *foundIndexPath = [NSIndexPath indexPathForRow:index inSection:indexPath.section];
					[indexPaths addObject:foundIndexPath];
				}
			}
			
			[array removeObjectsAtIndexes:removeIndexes];
			
			self.currentShowList = array;
		}
		
		if ([self.gameList indexOfObject:item] != NSNotFound)
		{
			NSMutableArray * array = [NSMutableArray arrayWithArray:self.gameList];
			[array removeObject:item];
			self.gameList = array;
		}
	}

	return indexPaths;
}

- (void)createRefreshHeader
{
	if (self.refreshHeaderView == nil)
	{
		UIScrollView *scrollView = self.tableView;
		if (scrollView)
		{
			
			EGORefreshTableHeaderView *refreshHeaderView  = [[EGORefreshTableHeaderView alloc]
															 initWithFrame:CGRectMake(0.0f,
																					  0.0f - scrollView.bounds.size.height,
																					  self.view.frame.size.width,
																					  scrollView.bounds.size.height)];
			self.refreshHeaderView = refreshHeaderView;
			self.refreshHeaderView.delegate = self;
			[scrollView addSubview:self.refreshHeaderView];
			[refreshHeaderView release];
		}
	}
	
}

- (void)createRefreshFooter
{
	if (self.refreshFooterView == nil)
	{
		UIScrollView *scrollView = self.tableView;
		if (scrollView)
		{			
			EGORefreshTableFooterView *refreshFooterView  = [[EGORefreshTableFooterView alloc]
															 initWithFrame:CGRectMake(0.0f,
																					  0,
																					  self.view.frame.size.width,
																					  65)];
			
			self.refreshFooterView = refreshFooterView;
			self.refreshFooterView.delegate = self;
			[scrollView addSubview:self.refreshFooterView];
			[refreshFooterView release];
		}
	}
}

- (void)enableRefreshHeader:(BOOL)enable
{
	self.refreshHeaderView.hidden = !enable;
}

- (void)enableRefreshFooter:(BOOL)enable
{
	self.refreshFooterView.hidden = !enable;
}

#pragma mark - local method

- (void)setLoading:(BOOL)loading
{
	if (loading == NO)
	{
		if (self.refreshHeaderView)
		{
			[self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
		}
		
		if (self.refreshFooterView)
		{
			[self.refreshFooterView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
		}
	}
	
	_loading = loading;
}

- (void)getGameListDidFinished:(NSNotification *)notification
{
    NSDictionary *dict = notification.userInfo;
    
    LMListParam *listParam = [dict objectForKey:LMListParamKey];
    if (listParam.context == self)
    {
        NSArray *list = [dict objectForKey:LMRESULT];
        NSError *error = [dict objectForKey:LMErrorKey];
        
        [self getGameListDidFinished:list error:error];
		
		self.loading = NO;
    }
}

- (void)reloadList
{
	self.gameList = nil;
	[self performSelector:@selector(loadFirstList) withObject:nil afterDelay:0.1];
}

- (void)loadMoreList
{
	self.loading = [self loadList:[self.gameList count] limit:10];
}

#pragma mark - override method
- (NSString *)gameListNotificationName
{
    return @"";
}

- (BOOL)loadList:(NSInteger)start limit:(NSInteger)limit
{
    return NO;
}

- (NSArray *)getShowList
{
    return nil;
}

- (NSArray *)getAssociateItems:(id)item
{
	return [NSArray arrayWithObject:item];
}

- (void)getGameListDidFinished:(NSArray *)list error:(NSError *)error
{

}

- (NSString *)getCellIdentifierByItem:(id)item
{
    return nil;
}

- (void)updateCell:(UITableViewCell *)cell withItem:(id)item
{
    
}

- (void)didSelectCell:(UITableViewCell *)cell withItem:(id)item
{
    
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id item = [self itemAtIndexPath:indexPath];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (item && cell)
    {
        [self didSelectCell:cell withItem:item];
    }
}

#pragma mark - UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	//	LOG_METHOD;
	[self.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
	[self.refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	//	LOG_METHOD;
	[self.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	[self.refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.currentShowList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForIdentifier:(NSString *)cellIdentifier
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:cellIdentifier
                                              owner:self
                                            options:nil] objectAtIndex:0];
    }
    
    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath)
    {
        id item = [self itemAtIndexPath:indexPath];
        NSString *identifier = [self getCellIdentifierByItem:item];
        if (item && identifier)
        {
            cell = [self tableView:tableView cellForIdentifier:identifier];
            [self updateCell:cell withItem:item];
        }
    }
    
    return cell;
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{
	//	LOG_METHOD;
	if (!self.loading)
	{
		[self reloadList];
	}
	//	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.5];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
	//	LOG_METHOD;
	return self.loading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	//	LOG_METHOD;
	return [NSDate date]; // should return date data source was last changed
}


#pragma mark -
#pragma mark EGORefreshTableFooterDelegate Methods

- (void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView*)view
{
	//	LOG_METHOD;
	if (!self.loading)
	{
		[self loadMoreList];
	}
	//	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.5];
}

- (BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView*)view
{
	//	LOG_METHOD;
	return self.loading; // should return if data source model is reloading
	
}

@end
